#include "UDPGroup.h"

UDPGroup::UDPGroup(QString ip, int port, QWidget* parent)
	:QWidget(parent)
{
	lb_port = new QLabel(QString::number(port));
	initGUI();
	this->port = port;
	this->ip = ip;
	lb_ip->setText(this->ip);

	socket = new QUdpSocket(this);
	socket->bind(QHostAddress::AnyIPv4, port, QUdpSocket::ShareAddress);
	socket->joinMulticastGroup(QHostAddress(ip));
	connect(btn_send, &QPushButton::clicked, this, &UDPGroup::SendMessage);
	connect(socket, &QUdpSocket::readyRead, this, &UDPGroup::ReceivedMessage);
}

void UDPGroup::initGUI()
{
	/* 初始化GroupBox */
	mainLayout = new QGridLayout(this);
	top_layout = new QGridLayout();
	center_layout = new QGridLayout();
	bottom_layout = new QGridLayout();
	topBox = new QGroupBox("Socket状态");
	centerBox = new QGroupBox("数据接收与提示窗口");
	bottomBox = new QGroupBox("数据发送窗口");
	below_bottom_layout = new QGridLayout();
	lb_ip = new QLabel();
	topBox->setLayout(top_layout);
	centerBox->setLayout(center_layout);
	bottomBox->setLayout(bottom_layout);
	mainLayout->addWidget(topBox, 0, 0);
	mainLayout->addWidget(centerBox, 1, 0);
	mainLayout->addWidget(bottomBox, 2, 0);
	mainLayout->addLayout(below_bottom_layout, 3, 0);
	mainLayout->setRowStretch(1, 1);
	mainLayout->setRowStretch(2, 1);

	/* 初始化控件 */
	top_layout->addWidget(new QLabel("组播端口："), 0, 1);
	top_layout->addWidget(lb_ip, 0, 2);
	top_layout->addWidget(new QLabel("组播端口："), 0, 3);
	top_layout->addWidget(lb_port, 0, 4);
	top_layout->setSpacing(10);
	top_layout->setColumnStretch(0, 1);

	t_receive = new QTextEdit();
	t_receive->setReadOnly(true);
	center_layout->addWidget(t_receive);

	t_send = new QTextEdit();
	bottom_layout->addWidget(t_send);

	btn_send = new QPushButton("发送");
	below_bottom_layout->addWidget(btn_send, 0, 1);
	below_bottom_layout->setColumnStretch(0, 1);

}

void UDPGroup::SendMessage()
{
	socket->writeDatagram(t_send->toPlainText().toUtf8(),QHostAddress(ip),port);
	t_receive->append("本地端口[" + QString::number(port) + "]【发送】: " + t_send->toPlainText());
}

void UDPGroup::ReceivedMessage()
{
	QByteArray datagram;
	datagram.resize(socket->pendingDatagramSize());
	QHostAddress sender;
	quint16 sender_port;
	socket->readDatagram(datagram.data(), datagram.size(), &sender, &sender_port);
	QString str = sender.toString().split(":").last();
	t_receive->append(str + ":" + QString::number(sender_port) + "【接收】: " + datagram);
	
}
